import { CountComponent } from './../../../shared/components/count/count.component';
import {
  Component,
  Input,
  OnInit,
  Output,
  EventEmitter,
  ViewChild,
  ChangeDetectionStrategy,
} from '@angular/core';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { ProductService } from '../../service/product.service';
import { Store } from '@ngrx/store';
import { CartItem } from 'src/app/shared/ngrx/cart-store/cart.reducer';
import { getStateSlice } from 'src/app/shared/ngrx/cart-store/cart.selector';
import { productAdd } from 'src/app/shared/ngrx/cart-store/cart.action';

@Component({
  selector: 'app-product-detail',
  templateUrl: './product-detail.component.html',
  styleUrls: ['./product-detail.component.less'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ProductDetailComponent implements OnInit {
  @Input() visible: boolean = false;
  @Input() id!: string;
  @Output() isCancel = new EventEmitter();
  @ViewChild(CountComponent) countComp!: CountComponent;
  selectedProductIndex: number = 0;
  count: number = 1;
  productList$!: Observable<Array<any>>;
  constructor(
    private product: ProductService,
    private store: Store<{ cartList: CartItem[] }>
  ) {}

  ngOnInit() {
    this.productList$ = this.product.handleGetProductDetail(this.id).pipe(
      map(({ data }: any) => data),
      map((data: any) => data.productDetail)
    );
  }
  ngOnDestroy(): void {}
  handleCancel() {
    this.visible = false;
    this.isCancel.emit(true);
  }
  handleOrderItemClick(index: number) {
    this.selectedProductIndex = index;
    this.countComp.handleInitialization();
  }
  getCount(count: number) {
    this.count = count;
  }
  handleAddToCartClick(product: any) {
    let cartList: CartItem[] = [];
    let item = JSON.parse(JSON.stringify(product));
    item.count = this.count;
    item.selected = false;
    cartList.push(item);
    this.store.dispatch(productAdd({ cartItem: item }));
    this.handleCancel();
  }
}
